package weiyao.xinxidasai.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import weiyao.xinxidasai.DTO.FileTreeNode;
import weiyao.xinxidasai.DTO.Result;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import weiyao.xinxidasai.Utils.ThreadLocal.UserHolder;

import weiyao.xinxidasai.pojo.FilesFolder;
import weiyao.xinxidasai.service.FileService;
import weiyao.xinxidasai.service.FolderService;

import javax.annotation.Resource;
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
@Slf4j
@RestController
@RequestMapping("/files")
public class FileController {

    @Resource
    private FileService fileService;
    @Resource
    private FolderService folderService;



    //删除文件
    @DeleteMapping("/{filesId}")
    public Result deleteFile(@PathVariable Long filesId) {
        return fileService.deleteFile(filesId);
    }

    //文件上锁
    @PostMapping("/lock")
    public Result lockFile(@RequestParam Long filesId,
                           @RequestParam String password) {
        if (checkInput(password)) {
            return Result.fail("非法参数或者弱密码");
        }
        return fileService.lockFile(filesId, password);
    }

    //文件上锁
    @PostMapping("/lockone")
    public Result lockFileFace(@RequestParam Long filesId) {

        return fileService.lockFileFace(filesId);
    }

    //文件解锁
    @PostMapping("/unlock")
    public Result unlockFile(@RequestParam Long filesId,
                             @RequestParam String password) {
        if (checkInput(password)) {
            return Result.fail("非法参数或者弱密码");
        }

        return fileService.unlockFile(filesId, password);
    }
    //文件解锁(人脸)
    @PostMapping("/unlockWithFace")
    public Result unlockWithFace(@RequestParam("file") MultipartFile file,
                             @RequestParam("filesId") Long filesId) {


        return fileService.unlockFileWithFace(file,filesId);
    }

    //文件重命名
    @PutMapping("/rename")
    public Result renameFile(@RequestParam Long filesId,
                             @RequestParam String newName) {
        if (checkInput(newName)) {
            return Result.fail("非法参数或者弱密码");
        }
        return fileService.renameFile(filesId, newName);
    }


    //模糊搜索文件
    @GetMapping("/search")
    public List<FileTreeNode> searchFiles(@RequestParam String keyword) {
        if (checkInput(keyword)) {
            return null;
        }
        // 从线程获取当前用户
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return null;
        }
        return fileService.searchFileTreesByKeyword(userId, keyword);
    }

    //更改目录
    @PutMapping("/move")
    public Result moveFile(@RequestParam Long filesId,
                           @RequestParam Long targetFolderId) {

        // 验证目标文件夹是否存在
        FilesFolder targetFolder = folderService.getFolderById(targetFolderId);
        if (targetFolder == null) {
            return Result.fail("目标文件夹不存在");
        }
        return fileService.moveFile(filesId, targetFolderId);
    }


    public Result FilesCheck(MultipartFile file, Long folderId, Long userId) {
        if (file.isEmpty()) {
            return Result.fail("文件不能为空");
        }
        List<FilesFolder> userFolders = folderService.getPathbyuserid(userId);
        // 检查folderId是否属于当前用户的文件夹
        boolean folderBelongsToUser = false;
        for (FilesFolder folder : userFolders) {
            if (folder.getFolderId().equals(folderId)) {
                folderBelongsToUser = true;
                break;
            }
        }
        if (!folderBelongsToUser) {
            return Result.fail("无权在此目录上传文件");
        }
        // 检查该目录下是否已存在同名文件
        String fileName = file.getOriginalFilename();
        if (fileService.fileExistsInFolder(fileName, folderId)) {
            return Result.fail("该目录下已存在同名文件");
        }
        return null;
    }

    private boolean checkInput(String password) {
        // 基础空值校验
        if (password == null || password.trim().isEmpty()) {
            return false;
        }

        String s = password.toLowerCase();//统一转为小写
        String badStr =
                "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|" +
                        "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
                        "information_schema.columns|table_schema|union|where|order|by|" +
                        "'\\*|\\;|\\-|\\--|\\+|\\,|\\//|\\/|\\%|\\#";//过滤掉的sql关键字，特殊字符前面需要加\\进行转义
        //使用正则表达式进行匹配
        boolean matches = s.matches(badStr);
        return matches;

    }
}